package SwordOffer2;

import java.util.HashMap;

public class day4_3 {
    /*
     * 1.循环遍历数组计算中心下标右边数组之和，创建HashMap集合用于标记相同的最小中心下标的位置
     * 2.循环遍历数组，i指向当前下标 :1.rightSum-nums[i],判断leftSum是否等于rightSum,相等时，
     *   判断hashmap是否有leftSum的值，若包含，res记录hashmap中key为leftSum的value值，
     *   若不包含hashmap保存当前leftSum的值和i下标，leftSum累计当前nums[i]
     * 3.返回值res
     * */
    public int pivotIndex(int[] nums) {
        int rightSum = 0;
        int leftSum = 0;
        int res = -1;
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            rightSum += nums[i];
        }
        for (int i = 0; i < nums.length; i++) {
            rightSum -= nums[i];
            if (leftSum == rightSum) {
                if (map.containsKey(leftSum)) {
                    res = map.get(leftSum);
                } else {
                    res = i;
                    map.put(leftSum, i);
                }
            }
            leftSum += nums[i];
        }
/*        for (int i = 0; i < nums.length; i++) {
            int rightSum = 0;
            for (int j = i + 1; j < nums.length; j++) {
                rightSum += nums[i];
            }
            if (leftSum == rightSum) {
                if (map.containsKey(leftSum)) {
                    res = map.get(leftSum);
                } else {
                    res = i;
                    map.put(leftSum, i);
                }
            }
            leftSum += nums[i];
        }*/
        return res;
    }
}
